package JZOffer;

/**
 * 剑指 Offer 18. 删除链表的节点
 * 给定单向链表的头指针和一个要删除的节点的值，定义一个函数删除该节点。
 *
 * 返回删除后的链表的头节点。
 * **/
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
//单指针
class Solution18_1 {
    public ListNode deleteNode(ListNode head, int val) {
        //设置虚拟头节点
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode cur = dummy;

        while (cur.next != null) {
            if (cur.next.val == val){
                //当val为最后一个节点时
                if (cur.next.next == null) {
                    cur.next = null;
                    break;
                }
                cur.next = cur.next.next;
            }
            cur = cur.next;
        }
        return dummy;
    }
}
//双指针
class Solution18_2 {
    public ListNode deleteNode(ListNode head, int val) {
        if (head.val == val) return head.next;
        ListNode pre = head, cur = head.next;

        while (cur != null && cur.val != val) {
            pre = cur;
            cur = cur.next;
        }
        if (cur != null) pre.next = cur.next;
        return head;
    }
}


